<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>外呼计划</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
        <el-button size="small" type="success" icon="el-icon-refresh" @click="syncList()">同步</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column prop="taskid" label="任务ID" width="200">
      </el-table-column>
      <el-table-column prop="name" label="任务名称" width="200">
      </el-table-column>
      <el-table-column prop="calledNumber" label="外呼号码" width="100">
      </el-table-column>
      <el-table-column prop="totCallsuc" label="已呼数" width="100">
      </el-table-column>
      <el-table-column prop="totFailure" label="未接数" width="80">
      </el-table-column>
      <el-table-column prop="totTocustomer" label="转接数" width="80">
      </el-table-column>
      <el-table-column prop="totCallsucRate" label="已呼率" width="80">
      </el-table-column>
      <el-table-column prop="totSuccessRate" label="已接通率" width="80">
      </el-table-column>
      <el-table-column prop="totTocustomerRate" label="转接率" width="100">
      </el-table-column>
      <el-table-column prop="taskStatus" label="状态" width="100">
      </el-table-column>
      <el-table-column prop="lastBeginTime" label="最后启动时间" width="150">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="success" @click="refresh(scope.$index, scope.row)">刷新</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <!-- 新增界面 -->
    <el-dialog :title="'新增'" :model="addForm" :visible.sync="addFormVisible" :close-on-click-modal="false" width="60%"
               @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="addForm" ref="addForm" :rules="rules" size="mini">
        <el-form-item label="所属公司" prop="email">
          <el-input size="small" disabled v-model="addForm.companyName" placeholder="请输入所属公司"/>
        </el-form-item>
        <el-form-item label="计划名称" prop="name">
          <el-input size="small" v-model="addForm.name" placeholder="请输入计划名称"/>
        </el-form-item>
        <el-form-item label="外线号码" prop="calledNumber">
          <el-select style="width: 100%" v-model="addForm.calledNumber" placeholder="请选择外线号码">
            <el-option :label="item.nature.desc + '('+ item.pstnnumber +')'" :value="item.pstnnumber"
                       v-for="(item, index) in pstns" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属问卷" prop="surveyId">
          <el-autocomplete style="width: 100%" size="small" v-model="addForm.surveyName"
                           :fetch-suggestions="querySearchAsync" @select="handleSelect" auto-complete="off"
                           placeholder="请输入问卷名称"/>
        </el-form-item>
        <el-form-item label="最大并发" prop="maxConcurrentNum">
          <el-input size="small" type="number" v-model="addForm.maxConcurrentNum" auto-complete="off"
                    placeholder="请输入最大并发"/>
        </el-form-item>
        <el-form-item label="转接类型" prop="transType">
          <el-select style="width: 49%" v-model="addForm.transType" placeholder="请选择转接类型">
            <el-option :label="item.name" :value="item.id"
                       v-for="(item, index) in [{id: 2, name: '队列'}]" :key="index"></el-option>
          </el-select>

          <el-select style="width: 50%" v-model="addForm.transName" placeholder="请选择转接">
            <el-option :label="item.name" :value="item.name"
                       v-for="(item, index) in queueNames" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("addForm")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('addForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 修改界面 -->
    <el-dialog :title="'修改外呼参数'" :model="editForm" :visible.sync="editFormVisible" :close-on-click-modal="false"
               width="60%"
               @click='closeDialog("editForm")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules" size="mini">
        <el-form-item label="所属公司" prop="email">
          <el-input size="small" disabled v-model="editForm.companyName" placeholder="请输入所属公司"/>
        </el-form-item>
        <el-form-item label="计划名称" prop="name">
          <el-input size="small" disabled v-model="editForm.name" placeholder="请输入计划名称"/>
        </el-form-item>
        <el-form-item label="外线号码" prop="calledNumber">
          <el-select style="width: 100%" v-model="editForm.calledNumber" placeholder="请选择外线号码" @change="editFormChange">
            <el-option :label="item.nature.desc + '('+ item.pstnnumber +')'" :value="item.pstnnumber"
                       v-for="(item, index) in pstns" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最大并发" prop="maxConcurrentNum">
          <el-input size="small" type="number" v-model="editForm.maxConcurrentNum" auto-complete="off"
                    @change="editFormChange"
                    placeholder="请输入最大并发"/>
        </el-form-item>
        <el-form-item label="转接类型" prop="transType">
          <el-select style="width: 49%" v-model="editForm.transType" disabled placeholder="请选择转接类型">
            <el-option :label="item.name" :value="item.id"
                       v-for="(item, index) in [{id: '2', name: '队列'}]" :key="index"></el-option>
          </el-select>

          <el-select style="width: 50%" v-model="editForm.transName" placeholder="请选择转接" @change="editFormChange">
            <el-option :label="item.name" :value="item.name"
                       v-for="(item, index) in queueNames" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否校验" prop="calledNumber">
          <el-select style="width: 100%" v-model="editForm.isValid" placeholder="是否校验" @change="validFormChange">
            <el-option :label="item.name" :value="item.id"
                       v-for="(item, index) in [{id: '0', name: '否'}, {id: '1', name: '是'}]" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {pstnList, queueAll, surveyList} from "../../../api/baseMG";
  import Pagination from '../../../components/Pagination'
  import {SyncList, TaskDelete, TaskEdit, TaskList, TaskRefresh, TaskSave} from "../../../api/cti";
  import {getStore} from "../../../utils/util";

  export default {
    data() {
      return {
        list: [],
        editFormVisible: false,
        addFormVisible: false,
        editTitle: "",
        loading: false,
        editForm: {
          transType: 2,
          maxConcurrentNum: 1
        },
        addForm: {
          transType: 2,
          maxConcurrentNum: 1
        },
        rules: {},
        // 分页参数
        pageParams: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        searchParams: {
          page: 1,
          perPage: 10,
          orderBy: "last_begin_time desc",
          filters: [
            {
              showAble: false,
              readonly: true,
              placeholder: "默认",
              fieldName: "companyId",
              compare: "=",
              fieldValue: getStore("userInfo").companyId
            },
            {
              showAble: true,
              readonly: false,
              placeholder: "外呼计划ID",
              fieldName: "taskid",
              compare: "like",
              fieldValue: ""
            }
          ],
          isLock: ''
        },
        pstns: [],
        queueNames: []

      }
    },
    created() {
      this.search();
      this.initQueueNames();
    },
    // 注册组件
    components: {
      Pagination
    },
    methods: {
      validFormChange() {
        if (this.editForm.isValid === 1) {
          this.editForm.xintf = 'http://192.168.0.180:10008/survey/api/valid/' + this.editForm.surveyId;
        }
        if (this.editForm.isValid === 0) {
          this.editForm.xintf = 'http://192.168.0.180:10008/survey/api/validPass/' + this.editForm.surveyId;
        }
        TaskEdit(this.editForm).then(resp => {
          if (resp.success) {
            this.$message({
              type: 'success',
              message: resp.msg
            });
            this.editFormVisible = false;
            this.search();
          }
        })
      },
      editFormChange() {
        TaskEdit(this.editForm).then(resp => {
          if (resp.success) {
            this.$message({
              type: 'success',
              message: resp.msg
            });
            this.editFormVisible = false;
            this.search();
          }
        })
      },
      initQueueNames() {
        let that = this;
        queueAll().then(resp => {
          for (let i = 0; i < resp.data.length; i++) {
            let d = resp.data[i];
            that.queueNames.push({id: d.queueNum, name: d.queueName})
          }
        })
      },
      handleSelect(item) {
        this.addForm.surveyId = item.id;
        this.addForm.surveyName = item.name;
      },
      querySearchAsync(queryString, cb) {
        surveyList({
          page: 1,
          perPage: 10,
          filters: [
            {fieldName: "companyId", compare: "=", fieldValue: getStore("userInfo").companyId},
            {fieldName: "name", compare: "like", fieldValue: queryString},
            {fieldName: "state", compare: "=", fieldValue: 2}
          ],
          isLock: ''
        }).then(resp => {
          this.selectProjectList = resp.data.list;
          for (let i = 0; i < this.selectProjectList.length; i++) {
            this.selectProjectList[i].value = this.selectProjectList[i].name;
            this.selectProjectList[i].surveyId = this.selectProjectList[i].id;
          }
          cb(this.selectProjectList);
        })
      },
      getPstnList() {
        pstnList({
          perPage: 1000,
          filters: [],
          isLock: ''
        }).then(resp => {
          this.pstns = resp.data.list;
        })
      },
      syncList() {
        this.$confirm('确定同步外呼计划数据吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          SyncList().then(resp => {
            this.$message({
              type: 'success',
              message: resp.msg
            });
          })
        }).catch(err => {

        })

      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog === 'editForm') {
          this.editFormVisible = false
        } else if (dialog === 'addForm') {
          this.addFormVisible = false
        } else if (dialog === 'unit') {
          this.unitAccessshow = false
        }
      },
      submitAddForm(params) {
        this.$refs[params].validate(valid => {
            if (valid) {
              TaskSave(this.addForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.addFormVisible = false;
                  this.editFormVisible = false;
                  this.search();
                } else {
                  this.$message.error(resp.msg);
                }
              }).catch(err => {
                this.$message.error(err.msg);
              })
            }
          }
        );
      },
      handleAdd() {
        this.addForm = {
          companyId: getStore("userInfo").companyId,
          companyName: getStore("userInfo").company,
          transType: 2,
          maxConcurrentNum: 1
        };
        this.getPstnList();
        this.addFormVisible = true;
      },
      // 分页插件事件
      callFather(param) {
        this.searchParams.page = param.currentPage;
        this.searchParams.perPage = param.pageSize;
        this.getList(this.searchParams);
      },
      handleEdit(index, row) {
        this.getPstnList();
        this.editForm = {
          id: row.id,
          companyName: row.companyName ? row.companyName : getStore("userInfo").company,
          companyId: row.companyId ? row.companyId : getStore("userInfo").companyId,
          name: row.name,
          taskid: row.taskid,
          hitRate: row.hitRate,
          acwTime: row.acwTime,
          redialTimes: row.redialTimes,
          minRedialInterval: row.minRedialInterval,
          maxRingTime: row.maxRingTime,
          calledNumber: row.calledNumber,
          xintf: row.xintf ? row.xintf : "0",
          isValid: row.isValid ? row.isValid : "0",
          maxConcurrentNum: row.maxConcurrentNum,
          transType: row.transType,
          transName: row.transName
        };
        this.editFormVisible = true
      },
      search() {
        this.getList(this.searchParams);
      },
      getList(params) {
        TaskList(params).then(resp => {
          if (resp.success) {
            this.list = resp.data.list;
            this.pageParams.currentPage = resp.data.pageNum;
            this.pageParams.pageSize = resp.data.pageSize;
            this.pageParams.total = resp.data.total;
          }
        })
      },
      refresh(index, row) {
        this.$confirm('确定要更新外呼计划吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          TaskRefresh(row.taskid).then(resp => {
            this.search();
          })
        });
      },
      deleteItem(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          TaskDelete(row.taskid).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.search(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
            .catch(err => {
              this.loading = false;
              this.$message.error('删除失败，请稍后再试！')
            })
        })
          .catch(err => {
            console.error(err);
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }
</style>
